package com.heixiu.gallery2

import android.Manifest
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.core.view.get
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import kotlinx.android.synthetic.main.fragment_photos_preview.*
import kotlinx.android.synthetic.main.photos_preview_item.view.*
import kotlinx.coroutines.*

/**
 * A simple [Fragment] subclass.
 */

const val WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 1

class PhotosPreviewFragment : Fragment() {
    val galleryViewModel by activityViewModels<GalleryViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_photos_preview, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        val photosPreviewAdapter = PhotosPreviewAdapter()
        viewPagerPhotosPreview.adapter = photosPreviewAdapter

        // 图片垂直滚动（默认图片是水平滚动）
        //viewPagerPhotosPreview.orientation = ViewPager2.ORIENTATION_VERTICAL

        galleryViewModel.photoListLiveData.observe(viewLifecycleOwner, Observer {
            photosPreviewAdapter.submitList(it)
            viewPagerPhotosPreview.setCurrentItem(arguments?.getInt("current_position") ?: 0, false)
        })

        viewPagerPhotosPreview.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            @SuppressLint("SetTextI18n")
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                textViewPhotosPreview.text = "${position + 1} / ${galleryViewModel.photoListLiveData.value?.size}"
            }
        })

        imageViewDownloadPhoto.setOnClickListener {
            if (Build.VERSION.SDK_INT < 29 && ContextCompat.checkSelfPermission(requireContext(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), WRITE_EXTERNAL_STORAGE_REQUEST_CODE)
            } else {
                viewLifecycleOwner.lifecycleScope.launch {
                    savePhoto()
                }
            }
        }
    }

    private suspend fun savePhoto() {
        withContext(Dispatchers.IO) {
            val holder = (viewPagerPhotosPreview[0] as RecyclerView)
                .findViewHolderForAdapterPosition(viewPagerPhotosPreview.currentItem)
                    as PhotosViewHolder
            val bitmap = holder.itemView.imageViewPhotosPreview.drawable.toBitmap()
            val uri = requireContext().contentResolver
                .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ContentValues())
                ?: kotlin.run {
                    MainScope().launch { showMsg("图片保存失败") }
                    return@withContext
                }
            requireContext().contentResolver.openOutputStream(uri as Uri).use {
                if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, it)) {
                    MainScope().launch { showMsg("图片保存成功") }
                } else {
                    MainScope().launch { showMsg("图片保存失败") }
                }
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode) {
            WRITE_EXTERNAL_STORAGE_REQUEST_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    viewLifecycleOwner.lifecycleScope.launch {
                        savePhoto()
                    }
                } else {
                    showMsg("图片保存失败，您拒绝授权")
                }
            }
        }
    }

    private fun showMsg(msg: String) {
        Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show()
    }
}
